<template>
  <div>
    <el-dialog v-model="isShow" title="批量添加学生" width="600" center @close="closeHandler" >
      <el-upload
        class="upload-demo"
        drag
        action=""
        :auto-upload="false"
        :on-change="onChange"
        ref="upload"
        :show-file-list="false"
        v-if="stuList.length<=0"
        v-loading="isLoading" 
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">
          可拖拽上传，在上传之前，请下载模板
          <em @click.stop="getMbHandler">下载模板</em>
        </div>
        <template #tip>
          <div class="el-upload__tip">只支持excel文件，且不超过50Mb</div>
        </template>
      </el-upload>
      <el-table v-else border :data="stuList" >
        <el-table-column align="center" label="序号" type="index" width="80" ></el-table-column>  
        <el-table-column align="center" label="学号" prop="stuNum" ></el-table-column>
        <el-table-column align="center" label="姓名" prop="stuName" ></el-table-column>
        <el-table-column align="center" label="班级" prop="className" ></el-table-column>
        <el-table-column align="center" label="操作"  >
          <template #default="{row}" >
            <el-button type="danger" :icon="Delete" size="small" @click="deleteHandler(row)" >删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="isShow = false">取消</el-button>
          <el-button type="primary" @click="AddStuList">
            添加
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref } from "vue";
import { UploadFilled , Delete } from "@element-plus/icons-vue";

import axios from "axios";
import { ElMessage } from "element-plus";
import { parseExcelFile } from "@/utiles/time";
import { batchAddStudentAPI } from "@/api/student";
const emits = defineEmits(['getStudentList'])
let isShow = defineModel();
let upload = ref();
let stuList = ref([]);
let isLoading=ref(false);
let isLoading2 = ref(false)
//获取模板
const getMbHandler = async () => {
  try {
    // 发送GET请求到后端的文件URL
    const response = await axios({
      method: "get",
      url: "http://localhost:3000/excel/stuMb.xls",
      responseType: "blob", // 告诉axios我们期望得到一个blob响应
    });

    // 创建一个Blob对象，用于在浏览器中处理二进制数据
    const url = window.URL.createObjectURL(new Blob([response.data]));

    // 创建一个a标签用于下载
    const link = document.createElement("a");
    link.href = url;
    link.setAttribute("download", "stuMb.xlsx"); // 设置下载文件的名称
    document.body.appendChild(link);
    link.click(); // 模拟点击下载链接

    // 清理
    window.URL.revokeObjectURL(url);
    document.body.removeChild(link);
  } catch (error) {
    console.error("Error downloading the file:", error);
    ElMessage.error("下载文件失败");
  }
};
const onChange = async (file) => {
  //判断是否为xls或者xlsx文件，且大小小于50mb
 let type = file.name.split(".")[1];
  if (type=="xls"||type=="xlsx" && file.raw.size < 50 * 1024 * 1024) {
    // 文件类型正确，可以上传
    // 执行上传操作
    isLoading.value = true;
    let result = await parseExcelFile(file.raw);
    let jsonData = [];

    // 遍历数据列表
    for (let i = 0; i < result.length; i++) {
      let entry = result[i];
      // 假设entry[0]是学号，entry[1]是姓名，entry[2]是班级名称
      let stuNum = entry[0];
      let name = entry[1];
      let className = entry[2];

      // 创建一个新的JSON对象并添加到jsonData数组中
      jsonData.push({
        stuNum: stuNum,
        stuName: name,
        className: className,
      });
    }
    jsonData.splice(0, 1);
    isLoading.value = false
    stuList.value = jsonData;
  
  } else {
    // 文件类型错误，提示用户
    ElMessage.error("文件类型错误，请上传Excel文件");
    //清空文件
  }
};
const closeHandler = ()=>{
  stuList.value = [];
  isShow.value = false;
}
const AddStuList = async ()=>{
  isLoading2.value = true;
  let result = await batchAddStudentAPI({stuList:stuList.value});
  if(result.code == 200) {
    ElMessage.success('添加成功')
    closeHandler();
    emits('getStudentList')
  }
  isLoading2.value = false;
}
const deleteHandler = (row)=>{
  stuList.value = stuList.value.filter(item=>item.stuNum!=row.stuNum)
}
</script>

<style lang="scss" scoped></style>
